<?php
namespace app\common\business;

use app\common\model\mysql\GoodsSku as goodsSkuModel;
class GoodsSku extends BusiBase{
	protected $model = null;
	public function __construct(){
		$this->model = new goodsSkuModel();
	}
 	
	// 批量添加sku数据
	public function saveAll($data){
		if(!$data['skus']){
			return false;
		}

		//数据入sku表
		foreach($data['skus'] as $value){
			$insertSkuData[] = [
				'goods_id'=>$data['goods_id'],
				'specs_value_ids'=>$value['propvalnames']['propvalids'],
				'price'=>$value['propvalnames']['skuSellPrice'],
				'cost_price'=>$value['propvalnames']['skuMarketPrice'],
				'stock'=>$value['propvalnames']['skuStock'],
			];
		}
		//dump($insertSkuData);exit;
		try{
			$result = $this->model->saveAll($insertSkuData);
			//dump($result->toArray());exit;
			return $result->toArray();
		}catch(\Exception $e){
			//记录日志
			return false;
		}
		return true;
	}

	

	// 根据ID获取记录
	public function getById($id){
		$result = $this->model->find($id);
		if(empty($result)){
			return [];
		}
		return $result->toArray();
	}

	//根据skuId获取goods_sku和goods相关信息
	public function getNormalSkuAndGoods($skuId){
		$result = $this->model->with('goods')->find($skuId);
		//dump($result->toArray());exit;
		if(!$result){
			return [];
		}
		$result = $result->toArray();
		if($result['status'] != config('status.mysql.normal')){
			return [];
		}
		return $result;
	}

	public function getSkusByGoodsId($goodsId){
		
		if(!$goodsId){
			return [];
		}

		try{
			$skus = $this->model->getNormalByGoodsId($goodsId);
		}catch(\Exception $e){
			return [];
		}
		
		return $skus->toArray();
	}

	public function getNormalInIds($ids){
		if(!$ids){
			return [];
		}

		try{
			$result = $this->model->getNormalInIds($ids); 
		}catch(\Exception $e){
			return [];
		}
		$result = $result->toArray();
		if(!$result){
			return [];
		}
		return $result;
	}

	//更新库存
	public function updateStock($data){
		foreach ($data as $key => $value) {
			$this->model->decStock($value['id'],$value['num']);
		}
		return true;
	}
}